<template>
    <!-- 顶部内容, 书写在这里, 通过传送门(teleporter) 放在顶部内 -->
    <teleport to=".header">
      <SdyHeader @searchText="searchHandler" center="search" right="search"/>
    </teleport>
  
    <div class="sdy-search">
      <div v-if="searchList.length" class="search-list">
        <div class="top">
          <div class="title">最近搜索</div>
          <van-icon name="delete-o" @click="delHandler" />
        </div>
        <ul class="bottom zuijin">
          <li @click="clickHandler(item.keyword)" v-for="item in searchList" :key="item.wordid">{{ item.keyword }}</li>
        </ul>
      </div>
      <div class="search-list hot-search">
        <div class="top">
          <div class="title">热门搜索</div>
          <span @click="hotSearchIsShow = !hotSearchIsShow">{{ hotSearchIsShow ? '隐藏' : '显示' }}</span>
        </div>
        <ul v-if="hotSearchIsShow" class="bottom">
          <li @click="clickHandler(item.keyword)" v-for="item in hotSearchList" :key="item.wordid">
            {{ item.keyword }}
          </li>
        </ul>
        <div v-else class="not">
          已隐藏搜索发现
        </div>
      </div>
  
      <ul v-if="searchListIsShow" class="search-list-box">
        <li @click="clickHandler(item.brand)" v-for="item in searchContentList" :key="item.proid">
          <div class="title">
            {{ item.brand }}
          </div>
          <div class="tag">
            {{ item.category }}
          </div>
        </li>
      </ul>
    </div>
  </template>
  
  <script name="sdySearch" lang="ts" setup>
  import SdyHeader from '../../components/header.vue'
  import { ref, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { getHotSearchList, getSearchList } from '../../model/goods'
  
  const $myRouter = useRouter()
  
  // 定义接口
  interface SearchGoodsInfo {
    num?: number
    keyword?: string
    wordid?: string
  }
  
  interface GoodsInfo {
    img1?: string
    proid?: string
    proname?: string
    originprice?: number
    discount?: number
    [key: string]: any
  }
  
  interface Response<T> {
    code: string
    data: Array<T>
  }
  
  // 定义变量决定搜索框输入文本以后, 搜索列表盒子是否显示
  const searchListIsShow = ref<boolean>(false)
  
  // 定义变量, 决定热门搜索盒子是否显示
  const hotSearchIsShow = ref<boolean>(true)
  
  // 定义变量, 保存热门搜索列表
  const hotSearchList = ref<Array<SearchGoodsInfo>>([])
  
  // 获取热门搜索列表
  const getHotSearchListHandler = async () => {
    const res = await getHotSearchList()
    
    if ((res as unknown as Response<SearchGoodsInfo>).code !== '200') return
    res.data.forEach((item: SearchGoodsInfo) => {
      // 如果有 keyword 关键字, 那么就添加到 hotSearchList 内
      item.keyword && hotSearchList.value.push(item)
    })
  }
  
  // 准备一个变量表示最近搜索列表
  const searchList = ref<SearchGoodsInfo[]>([])
  
  // 从 localStorage 内拿到最近搜索列表
  const getSearchListHandler = () => {
    const res = JSON.parse(window.localStorage.getItem('searchList') || '[]')
    searchList.value = res as SearchGoodsInfo[]
  }
  
  // 准备一个变量, 表示搜索内容列表
  const searchContentList = ref<Array<GoodsInfo>>([])
  
  // 实现实时搜索操作
  const searchHandler = async (str: string) => {
    // 发送请求, 请求对应内容渲染列表
    if (!str.trim()) {
      searchContentList.value = []
      searchListIsShow.value = false
      return
    }
    const res = await getSearchList(str)
    
    if ((res as unknown as Response<GoodsInfo>).code !== '200') return
    searchContentList.value = res.data
    // 让搜索列表显示出来
    searchListIsShow.value = true
  }
  
  // 点击跳转
  const clickHandler = (str?: string) => {
    // 把搜索关键字存储到数组内
    for (let i = searchList.value.length - 1; i >= 0; i--) {
      const index = searchList.value.findIndex(item => {
        return item.keyword === str
      })
      if (index !== -1) {
        searchList.value.splice(index, 1)
      }
    }
  
    searchList.value.unshift({
      wordid: Math.random.toString().slice(-8),
      keyword: str
    })
  
    window.localStorage.setItem('searchList', JSON.stringify(searchList.value))
  
    // 跳转连接
    $myRouter.replace({ path: '/list', query: { keyword: str } })
  }
  
  // 删除事件
  const delHandler = () => {
    window.localStorage.removeItem('searchList')
    searchList.value = []
  }
  
  onMounted(() => {
    getHotSearchListHandler()
    getSearchListHandler()
  })
  </script>
  
  <style scoped lang="scss">
  .sdy-search {
    width: 100%;
    height: 100%;
    background-color: #F6F6F6;
    position: relative;
  
    > .search-list {
      padding: 10px;
      background-color: #fff;
  
      > .top {
        height: 30px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 16px;
        margin-bottom: 10px;
      }
  
      > .bottom {
        display: flex;
        flex-wrap: wrap;
  
        > li {
          padding: 5px 15px;
          background-color: #f0f2f5;
          border-radius: 5px;
          margin: 0 8px 10px 0;
          font-size: 12px;
        }
      }
      ul li:nth-child(-n+3) {
        color: red;
        font-weight: 700;
      }
      .zuijin li:nth-child(n){
        font-weight: 400;
        color: #000;
      }
      > .not {
        height: 100px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
  
  .search-list-box {
    padding: 10px;
    background-color: #fff;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    box-sizing: border-box;
  
    > li {
      height: 32px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 14px;
  
      > .tag {
        font-size: 12px;
        padding: 5px 10px;
        border-radius: 5px;
        background-color: #F6F6F6;
      }
    }
  }
  </style>
  